package com.jackchen.common.filter;

import java.util.Date;
import java.util.HashMap;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpSession;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import org.apache.log4j.Logger;

import com.jackchen.util.DateUtils;

public class ProjectContextListener extends HttpServlet implements ServletContextListener,HttpSessionListener{

	private static final Logger log = Logger.getLogger(ProjectContextListener.class);
	
	public void contextInitialized(ServletContextEvent contextEvent){
		log.info("Now,Tomcat is creating ServletContext!----Tomcat正在创建ServletContext类实例,Tomcat web服务初始化开始！");
		contextEvent.getServletContext().setAttribute(LoginFilter.ONLINE_USERLIST, new HashMap<String,HttpSession>());
	}
	
	public void contextDestroyed(ServletContextEvent contextEvent){
		log.info("Now,Tomcat is destroying ServletContext----Tomcat正在销毁ServletContext类实例,Tomcat web服务开始停止！");
		contextEvent.getServletContext().removeAttribute(LoginFilter.ONLINE_USERLIST);
	}
	
	public void sessionCreated(HttpSessionEvent sessionEvent){
		log.info("Session Created!The session id is :"+sessionEvent.getSession().getId());
		log.info("Seesion:"+sessionEvent.getSession().getId()+" created time is:"+DateUtils.format(new Date()));
	}
	
	public void sessionDestroyed(HttpSessionEvent sessionEvent){
		HttpSession httpSession = sessionEvent.getSession();
		String userName = (String) httpSession.getAttribute(LoginFilter.SESSION_USER_NAME);
		log.info("Session:"+userName+"  is destroying now!");
		log.info("Destory time is:"+DateUtils.format(new Date()));
		if(userName!=null){
			ServletContext servletContext = httpSession.getServletContext();
			HashMap onLineList =  (HashMap)servletContext.getAttribute(LoginFilter.ONLINE_USERLIST);
			onLineList.remove(userName);
		}
	}
}
